//
//  BPCitySelectViewController.swift
//  BotuPanoram
//
//  Created by slowdony on 2019/11/13.
//  Copyright © 2019 Bicon. All rights reserved.
//

import UIKit
import CoreLocation
import SwiftyJSON

class SDCitySelectVC: UIViewController ,UITableViewDelegate,UITableViewDataSource, UITextFieldDelegate{
    @objc var selectResultBlock:((SDCityModel)->())?
    var isDepart=true
    var isSearch=false
    var cityListData:[SDCityModel]=[]
    override func viewDidLoad() {
        super.viewDidLoad()
        self .setupUI()
        self .cityNetWork()
        self .location()
    }
    
    lazy var citySelectVM: SDCitySelectVM = {
        let citySelectVM = SDCitySelectVM()
        
        return citySelectVM
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden=false
    }
    
    lazy var currentCityView:SDCitySelectHeadView = {
        let currentCityView  = SDCitySelectHeadView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 114+12))
         currentCityView.locationBtnClickBlock = {
            self.currentCityView .setLocationButtonState(state: .positioning)
            self .location()
        }
//        currentCityView.currentBtnClickBlock = {(sender:UIButton) in
//           let cityModel = SDCityModel()
//           var cityName = sender.titleLabel?.text
//           cityName = cityName?.replacingOccurrences(of: " ", with: "")
//           cityModel.name = cityName as NSString?
//            if let selectResultBlock = self.selectResultBlock {
//                selectResultBlock(cityModel)
//            }
//            self.navigationController? .popToRootViewController(animated: true)
//        }
        return currentCityView
    }()
    
    
    lazy var textFiled: UITextField = {
        let textFiled = UITextField(frame: CGRect(x: 30 , y:20+44+10, width:  kScreenW-60 , height: 40))
        textFiled.delegate = self
        textFiled.backgroundColor = UIColor.clear
        textFiled.font =  UIFont .systemFont(ofSize: 14)
        textFiled.textColor = ColorHex(0x2A2928)
        textFiled.clearButtonMode = UITextField.ViewMode.whileEditing
        textFiled.keyboardType = UIKeyboardType.default
        textFiled.autocorrectionType = UITextAutocorrectionType.no
        textFiled.returnKeyType = UIReturnKeyType.search
        textFiled.backgroundColor = ColorHex(0xF1F1F1)
        textFiled.layer.cornerRadius = 30/2
        textFiled.layer.masksToBounds = true
        textFiled.tintColor = ColorHex(0xFF6532)
        let placeholserAttributes = [NSAttributedString.Key.foregroundColor: ColorHex(0xAEAEAE),NSAttributedString.Key.font :  UIFont .systemFont(ofSize: 14)]
        textFiled.attributedPlaceholder = NSAttributedString(string: "请输入城市名称/拼音首字母",attributes: placeholserAttributes)
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 42, height: 40)
        let leftImageView = UIImageView()
        leftImageView.frame = CGRect(x: 16, y: 10, width:20, height: 20)
        leftImageView.image = UIImage.init(named: "图层22")
        leftView .addSubview(leftImageView)
        
        textFiled.leftView = leftView
        textFiled.leftViewMode = UITextField.ViewMode.always
        textFiled.addTarget(self, action: #selector(textFiledChangeValue(textField:)), for: UIControl.Event.editingChanged)
        return textFiled
    }()
    
    @objc func textFiledChangeValue(textField:UITextField) {
        guard let letter = textField.text?.uppercased() else {
            return
        }
        
        if self.citySelectVM.firstLetterArray.contains(letter) == true {
            self.searchCityByLetter(keyword: textFiled.text!)
        }else{
            self.searchCity(keyword: textFiled.text!)
        }
          
          
      }
    
    func searchCityByLetter(keyword:String){
        cityListData=[]
        if keyword == "" {
            isSearch=false
            tableView.reloadData()
        }else{
            let k=keyword.uppercased()
            for a in self.citySelectVM.allCityArr {
                for b in a {
                    if b.pinyin?.contains(k) == true{
                        cityListData.append(b)
                    }
                    
                }
            }
            isSearch=true
            tableView.reloadData()
        }
        
        
    }
    
    func searchCity(keyword:String){
        cityListData=[]
        if keyword == ""{
            isSearch=false
            tableView.reloadData()
        }else{
            for a in self.citySelectVM.allCityArr {
                for b in a {
                    if b.city?.contains(keyword) == true{
                        cityListData.append(b)
                    }
                    
                }
            }
            isSearch=true
            tableView.reloadData()
        }
        
        
    }
    
    
    
    func location(){
        let manage = SDLocationManager .shared
        manage .startPositing(vc: self)
        manage.cityPositionBlock = {(cityName:String ,error:String) -> Void in
            if (error.isEmpty){
               self.currentCityView .setCurrentCityButtonTitle(title: cityName)
               self.currentCityView .setLocationButtonState(state: .locateComplete)
            }else{
               self.currentCityView .setLocationButtonState(state: .locateFailure)
            }
        }
    }
    
  
    

    
    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: CGRect(x: 0, y: 20+44+58, width: SCREEN_WIDTH, height: SCREEN_HEIGHT-44-20-58-BottomSpaceHeigh)
            , style: UITableView.Style.plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.backgroundColor = UIColor.clear
        tableView.sectionIndexColor = ColorHex(0xFF6D3D)
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cellID")
        tableView.register(UINib(nibName: "SDHotCityTableViewCell", bundle: nil), forCellReuseIdentifier: "SDHotCityTableViewCell")
        return tableView
    }()
    
    lazy var leftBtn: UIButton = {
           let btn = UIButton()
           btn.frame = CGRect(x:15, y: 20, width: 30, height: 44)
           btn.setImage(UIImage.init(named: "支付方式-关闭"), for: UIControl.State.normal)
           btn .addTarget(self, action: #selector(popBtnClick), for: UIControl.Event.touchUpInside)
           return btn
       }()
    
    @objc func popBtnClick() {
        
        self.dismiss(animated: true, completion: nil)
    }
  
    
}



extension SDCitySelectVC{
    func setupUI() {
        self.view.backgroundColor = UIColor.white
        
        self.view.addSubview(leftBtn)
        let title=UILabel.init(frame: CGRect(x: 30, y: 20, width: SCREEN_WIDTH-60, height: 44))
        title.text="请选择航班城市"
        title.textAlignment = .center
        title.textColor=UIColor.black
        title.font=UIFont.boldSystemFont(ofSize: 18)
        self.view.addSubview(title)
        self.view.addSubview(textFiled)
        
        self.tableView.tableHeaderView = self.currentCityView;
        
        self.view .addSubview(self.tableView)
    }
}

// MARK:  tableview代理
extension SDCitySelectVC {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        if isSearch {
            self.tableView.tableHeaderView=nil
            return 1
        }else{
            self.tableView.tableHeaderView = self.currentCityView;
            return self.citySelectVM.firstLetterArray.count
        }
        
        
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        if section == 0 {
            if isSearch {
                return cityListData.count
            }
            
            return 1
        }
        
        return  self.citySelectVM.allCityArr[section-1].count
       
    }
    

    
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
       
        
        if indexPath.section == 0  {
            if isSearch {
                let cell  = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
                cell.textLabel?.text = cityListData[indexPath.row].city
                cell.textLabel?.font =  UIFont .systemFont(ofSize: 14)
                cell.textLabel?.textColor = ColorHex(0x2a2928)
                return cell
            }else{
                
                
                let cell:SDHotCityTableViewCell = tableView.dequeueReusableCell(withIdentifier: "SDHotCityTableViewCell") as! SDHotCityTableViewCell
                cell.isDepart=isDepart
                cell.dataArr=self.citySelectVM.hotCityArr
                cell.collectionView.reloadData()
                cell.dismissVC={[weak self] in
                    self?.dismiss(animated: true, completion: nil)
                }
                return cell
                
                
            }
           
          
        }else {
            
            let cityList=self.citySelectVM.allCityArr[indexPath.section-1]
            
            let cell  = tableView.dequeueReusableCell(withIdentifier: "cellID", for: indexPath)
            cell.textLabel?.text = cityList[indexPath.row].city
            cell.textLabel?.font =  UIFont .systemFont(ofSize: 14)
            cell.textLabel?.textColor = ColorHex(0x2a2928)
            cell.mtag=cityList[indexPath.row].code ?? ""
            return cell
        }
        
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if isSearch {
                return 40
            }
            
            return SDHotCityTableViewCell.cellHeight(data: self.citySelectVM.hotCityArr )
        }
        return 40
    }
    
    func sectionIndexTitles(for tableView: UITableView) -> [String]? {
        
        return (self.citySelectVM.firstLetterArray as! [String])
        
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if isSearch {
            return 0
        }
        return 52
    }
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 52))
        view.backgroundColor = UIColor.white
        
        let label = UILabel()
        label.frame = CGRect(x:16 , y: 20, width: 100, height: 20)
        label.backgroundColor = UIColor.clear
        label.textColor = ColorHex(0x2A2928)
        
        if isSearch {
            label.text=""
        }else{
            label.text = self.citySelectVM.firstLetterArray[section] as? String
        }
        
        
        label.textAlignment = NSTextAlignment.left
        label.font =  UIFont .systemFont(ofSize: 14)
        label.numberOfLines = 1
        view .addSubview(label)
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        let footView = UIView(frame: CGRect(x: 0, y: 0, width: kScreenW, height: 26))
        footView.backgroundColor = UIColor.white
        let view = UIView(frame: CGRect(x: 0, y: 14, width: kScreenW, height: 12))
        view.backgroundColor = ColorHex(0xF8F8F8)
        footView .addSubview(view)
        return footView
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if isSearch {
            return 0
        }
        return 26
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section != 0 || isSearch {
            let cell=tableView.cellForRow(at: indexPath)
            print(cell?.mtag)
            
            let dic=["cityName":cell?.textLabel?.text,"cityCode":cell?.mtag]
           
            if isDepart {
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "chooseDepart"), object: dic, userInfo: nil)
                
            }else{
                
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "chooseArrive"), object: dic, userInfo: nil)

            }
            self.dismiss(animated: true, completion: nil)
            
        }
        
    }
}
// MARK:BPHotCityCellDelegate
extension SDCitySelectVC{
    func hotCityCellDidSelectItemAt(cityModel: SDCityModel) {
        
        if let selectResultBlock = selectResultBlock {
            selectResultBlock(cityModel)
        }
        self.navigationController? .popToRootViewController(animated: true)
    }
}

//extension SDCitySelectVC:CLLocationManagerDelegate{
//    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//        guard let newLocation = locations.last
//            else {
//            print("失败1")
//            return
//        }
//            print(newLocation)//<+31.26514482,+121.61259089> +/- 50.00m (speed 0.00 mps / course -1.00) @ 2016/11/14 中国标准时间 14:49:51
//        if newLocation.horizontalAccuracy < 0 {
//            print("失败2")
//            return
//        }
//         geoCoder.reverseGeocodeLocation(newLocation) { (pls: [CLPlacemark]?, error: Error?) in
//            if error == nil {
//                guard let pl = pls?.first else {return}
//                print("22222\(pl.locality!)22222")//上海市
//
//                UserDefaults.standard .set(pl.locality, forKey: "locationCityName")
//                self.currentCityView .setCurrentCityButtonTitle(title: pl.locality ?? "")
//                self.currentCityView .setLocationButtonState(state: .locateComplete)
//            }else{
//                print("定位失败")
//                self.currentCityView .setLocationButtonState(state: .locateFailure)
//            }
//        }
//        manager.stopUpdatingLocation()
//    }
//
//    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
//        self.currentCityView .setLocationButtonState(state: .locateFailure)
//
////        let alert = LEEAlert.alert()
////        _ = alert.config
////            .leeTitle("伯图全景温馨提示您")
////            .leeContent("请开启定位服务,已便获取附近信息")
////            .leeAddAction({(action:LEEAction)in
////                action.title = "取消"
////                action.titleColor = ColorHex(0x919090)
////                action.type = .cancel
////            })
////            .leeAddAction({(action:LEEAction)in
////                action.title = "确定"
////                action.titleColor = ColorHex(0xFF8A41)
////                action.clickBlock = {
////                    let url = URL.init(string: UIApplication.openSettingsURLString)
////                    if UIApplication .shared .canOpenURL(url!){
////                        UIApplication.shared.open(url!, options: [:], completionHandler: nil)
////                    }
////                }
////            })
////            .leeShow()
//        manager.stopUpdatingLocation()
//    }
//
//}

extension SDCitySelectVC{
    func cityNetWork()  {
        self.citySelectVM.getHotCityByNetwork(callBack: {[weak self] isSuccess in
            if isSuccess {
                self?.tableView.reloadData()
            }
        })
    }
}
